/**
 * @description: 关闭页面
 */
export const closeWebPage = () => {
  if (navigator.userAgent.indexOf('MSIE') > 0) {
    if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
      window.opener = null;
      window.close();
    } else {
      window.open('', '_top');
      window.top?.close();
    }
  } else if (navigator.userAgent.indexOf('Firefox') > 0) {
    window.location.href = 'about:blank '; // 火狐默认状态非window.open的页面window.close是无效的
  } else {
    window.opener = null;
    window.open('', '_self', '');
    window.close();
  }
};

/**
 * @description: 判断是否是泰康环境
 */
export const isTKApp = () => navigator.userAgent.toLowerCase().indexOf('tk_') > -1;

/**
 * 关闭浏览器 app中返回
 */
export const webBackClick = () => {
  window.tyyNativeBus({
    serviceName: 'webBackClick',
    success: () => {
      console.log('webBackClick-success');
    },
    fail: (error: any) => {
      console.error('webBackClick-fail:::', error);
    },
  });
};

/**
 * 打开app相机或相册
 * mode 1 相机 2 相册
 * options 桥接参数
 * callback 回调
 */
export const openCameraOrAlbum = (mode: number, callback: Func, options = {}) => {
  const defaultOptions = {
    count: 1,
    needEdit: false,
    needBase64: true,
    faceImage: false,
  };
  const formatBase64 = (str: string) => `data:image/jpg;base64,${str.split(',')[0]}`;
  if (Number(mode) === 1) {
    window.tyyNativeBus({
      serviceName: 'getDeviceCamera',
      success(res: any) {
        console.log('getDeviceCamera-success');
        if (callback && res) {
          callback(formatBase64(res));
        }
      },
      fail(error: any) {
        console.error(error, 'getDeviceCamera-fail');
        if (callback) {
          callback(error, true);
        }
      },
      data: {
        ...defaultOptions,
        ...options,
      },
    });
  } else {
    window.tyyNativeBus({
      serviceName: 'getDeviceAlbum',
      success(res: any) {
        console.log('getDeviceAlbum-success');
        if (callback && res) {
          callback(formatBase64(res));
        }
      },
      fail(error: any) {
        console.error(error, 'getDeviceAlbum-fail');
        if (callback) {
          callback(error, true);
        }
      },
      data: {
        ...defaultOptions,
        ...options,
      },
    });
  }
};
